<template>
  <view v-if="visible" class="chat-modal-container" @click.self="close">
    <!-- 遮罩层 -->
    <view class="chat-modal-mask" @click="handleMaskClick"></view>
    
    <!-- 聊天弹窗 -->
    <view class="chat-modal" @click.stop>
      <!-- 头部 -->
      <view class="chat-header">
        <view class="drag-bar"></view>
        <view class="header-content">
          <view class="header-left">
            <text class="ai-avatar">🤖</text>
            <view class="ai-info">
              <text class="ai-name">AI小助手</text>
              <text class="ai-status">{{ loading ? '正在输入...' : '在线' }}</text>
            </view>
          </view>
          <text class="close-btn" @click="close">×</text>
        </view>
      </view>
      
      <!-- 消息列表 -->
      <scroll-view 
        class="message-list" 
        scroll-y 
        :scroll-into-view="scrollToView"
        :scroll-with-animation="true"
      >
        <view 
          v-for="(msg, index) in messages" 
          :key="index"
          :id="'msg-' + index"
          class="message-item"
          :class="{ 'message-ai': msg.role === 'assistant', 'message-user': msg.role === 'user' }"
        >
          <!-- AI消息：头像在左 -->
          <view v-if="msg.role === 'assistant'" class="avatar">
            <text class="avatar-icon">🤖</text>
          </view>
          
          <!-- 消息气泡 -->
          <view class="message-bubble">
            <text class="message-text">{{ msg.content }}</text>
            <text class="message-time">{{ formatTime(msg.timestamp) }}</text>
          </view>
          
          <!-- 用户消息：头像在右 -->
          <view v-if="msg.role === 'user'" class="avatar user-avatar">
            <text class="avatar-icon">👤</text>
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-indicator">
          <view class="loading-dots">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
          <text class="loading-text">AI正在思考...</text>
        </view>
        
        <!-- 底部占位，确保最后一条消息可见 -->
        <view class="bottom-spacer"></view>
      </scroll-view>
      
      <!-- 快捷问题（仅在没有消息时显示） -->
      <view v-if="showQuickQuestions && messages.length <= 1" class="quick-questions">
        <text class="quick-title">💡 你可以这样问我：</text>
        <view class="quick-list">
          <view 
            v-for="(q, idx) in quickQuestions" 
            :key="idx"
            class="quick-item"
            @click="sendQuickQuestion(q)"
          >
            <text class="quick-text">{{ q }}</text>
          </view>
        </view>
      </view>
      
      <!-- 输入区域 -->
      <view class="input-area">
        <view class="input-wrapper">
          <input 
            v-model="inputText"
            class="message-input"
            placeholder="输入你的问题..."
            :disabled="loading"
            confirm-type="send"
            @confirm="sendMessage"
            @focus="onInputFocus"
            @blur="onInputBlur"
          />
          <view 
            class="send-btn"
            :class="{ disabled: !canSend }"
            @click="sendMessage"
          >
            <text class="send-icon">{{ loading ? '⏳' : '📤' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import aiService from '@/services/ai.js'

export default {
  name: 'AIChatModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      messages: [],
      inputText: '',
      loading: false,
      scrollToView: '',
      quickQuestions: [],
      showQuickQuestions: true,
      conversationId: null,
      isInputFocused: false
    }
  },
  computed: {
    canSend() {
      return this.inputText.trim() && !this.loading
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initChat()
      }
    }
  },
  methods: {
    // 初始化聊天
    initChat() {
      if (this.messages.length === 0) {
        // 生成会话ID
        this.conversationId = 'conv_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        
        // 加载欢迎消息
        this.loadWelcomeMessage()
        
        // 加载快捷问题
        this.quickQuestions = aiService.getQuickQuestions()
      }
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    // 加载欢迎消息
    loadWelcomeMessage() {
      const userName = uni.getStorageSync('user_info')?.realName || ''
      const welcomeMsg = aiService.getWelcomeMessage(userName)
      
      this.messages.push({
        role: 'assistant',
        content: welcomeMsg,
        timestamp: new Date()
      })
    },
    
    // 关闭弹窗
    close() {
      this.$emit('update:visible', false)
      
      // 保存聊天记录
      if (this.conversationId && this.messages.length > 1) {
        aiService.saveConversation(this.conversationId, this.messages)
      }
    },
    
    // 点击遮罩关闭
    handleMaskClick() {
      this.close()
    },
    
    // 发送快捷问题
    sendQuickQuestion(question) {
      // 移除emoji
      const cleanQuestion = question.replace(/[🌶️📦🚚💰🎁👥]/g, '').trim()
      this.inputText = cleanQuestion
      this.sendMessage()
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.canSend) return
      
      const userMessage = this.inputText.trim()
      
      // 添加用户消息
      this.messages.push({
        role: 'user',
        content: userMessage,
        timestamp: new Date()
      })
      
      this.inputText = ''
      this.showQuickQuestions = false
      this.scrollToBottom()
      
      // 调用AI API
      this.loading = true
      
      try {
        const response = await aiService.sendMessage(userMessage, this.conversationId)
        
        if (response.code === 200 && response.data) {
          // 更新会话ID
          if (response.data.conversationId) {
            this.conversationId = response.data.conversationId
          }
          
          // 添加AI回复
          this.messages.push({
            role: 'assistant',
            content: response.data.reply || '抱歉，我暂时无法回答这个问题。',
            timestamp: new Date()
          })
          
          this.scrollToBottom()
        } else {
          throw new Error(response.message || 'AI回复失败')
        }
      } catch (error) {
        console.error('AI回复失败:', error)
        
        // 添加错误提示消息
        let errorMsg = '抱歉，我现在有点忙，请稍后再试 🙏'
        
        if (error.message && error.message.includes('401')) {
          errorMsg = '请先登录后再使用AI助手哦~'
        } else if (error.message && error.message.includes('网络')) {
          errorMsg = '网络连接失败，请检查网络后重试'
        }
        
        this.messages.push({
          role: 'assistant',
          content: errorMsg,
          timestamp: new Date()
        })
        
        this.scrollToBottom()
      } finally {
        this.loading = false
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const lastIndex = this.messages.length - 1
        if (lastIndex >= 0) {
          this.scrollToView = 'msg-' + lastIndex
        }
      })
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },
    
    // 输入框聚焦
    onInputFocus() {
      this.isInputFocused = true
      // 聚焦时滚动到底部
      setTimeout(() => {
        this.scrollToBottom()
      }, 300)
    },
    
    // 输入框失焦
    onInputBlur() {
      this.isInputFocused = false
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-modal-container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2000;
}

.chat-modal-mask {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.chat-modal {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 70vh;
  max-height: 1200rpx;
  background: #f5f5f5;
  border-radius: 32rpx 32rpx 0 0;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from { 
    transform: translateY(100%); 
  }
  to { 
    transform: translateY(0); 
  }
}

/* 头部 */
.chat-header {
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 16rpx 24rpx 20rpx;
  flex-shrink: 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .drag-bar {
    width: 80rpx;
    height: 8rpx;
    background: #ddd;
    border-radius: 4rpx;
    margin: 0 auto 16rpx;
  }
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  
  .ai-avatar {
    font-size: 48rpx;
    line-height: 1;
  }
  
  .ai-info {
    display: flex;
    flex-direction: column;
    gap: 4rpx;
  }
  
  .ai-name {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
  }
  
  .ai-status {
    font-size: 22rpx;
    color: #52c41a;
  }
  
  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60rpx;
    color: #999;
    line-height: 1;
    font-weight: 300;
  }
}

/* 消息列表 */
.message-list {
  flex: 1;
  padding: 24rpx 48rpx 24rpx 24rpx;
  overflow-y: auto;
  box-sizing: border-box;
}

.message-item {
  display: flex;
  margin-bottom: 32rpx;
  gap: 16rpx;
  animation: messageSlideIn 0.3s ease;
  width: 100%;
  flex-direction: row;
  align-items: flex-start;
  
  .avatar {
    width: 64rpx;
    height: 64rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    
    &.user-avatar {
      background: linear-gradient(135deg, #ffa726 0%, #ff8a00 100%);
    }
    
    .avatar-icon {
      font-size: 32rpx;
    }
  }
  
  .message-bubble {
    max-width: 70%;
    min-width: 100rpx;
    padding: 20rpx 24rpx;
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    word-wrap: break-word;
    overflow-wrap: break-word;
    
    .message-text {
      font-size: 28rpx;
      line-height: 1.6;
      word-break: break-word;
      white-space: pre-wrap;
      text-align: left;
    }
    
    .message-time {
      display: block;
      margin-top: 8rpx;
      font-size: 20rpx;
      text-align: left;
    }
  }
}

/* AI消息样式：整体靠左 */
.message-ai {
  justify-content: flex-start;
  
  .message-bubble {
    background: #fff;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .message-text {
      color: #333;
    }
    
    .message-time {
      color: #999;
    }
  }
}

/* 用户消息样式：整体靠右 */
.message-user {
  justify-content: flex-end;
  
  .message-bubble {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    max-width: 65%;
    
    .message-text {
      color: #fff;
    }
    
    .message-time {
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx;
  
  .loading-dots {
    display: flex;
    gap: 8rpx;
    
    .dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: 50%;
      background: #667eea;
      animation: dotPulse 1.4s infinite ease-in-out both;
      
      &:nth-child(1) {
        animation-delay: -0.32s;
      }
      
      &:nth-child(2) {
        animation-delay: -0.16s;
      }
    }
  }
  
  .loading-text {
    font-size: 24rpx;
    color: #999;
  }
}

@keyframes dotPulse {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.3;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 快捷问题 */
.quick-questions {
  background: #fff;
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
  flex-shrink: 0;
  
  .quick-title {
    display: block;
    font-size: 24rpx;
    color: #999;
    margin-bottom: 16rpx;
  }
  
  .quick-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
  }
  
  .quick-item {
    padding: 12rpx 20rpx;
    background: #f5f5f5;
    border-radius: 24rpx;
    border: 2rpx solid transparent;
    transition: all 0.3s ease;
    
    &:active {
      background: linear-gradient(135deg, #ffe6e8 0%, #fff5f5 100%);
      border-color: #667eea;
    }
    
    .quick-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

/* 输入区域 */
.input-area {
  background: #fff;
  padding: 20rpx 24rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  flex-shrink: 0;
  
  .input-wrapper {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  
  .message-input {
    flex: 1;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;
  }
  
  .send-btn {
    width: 72rpx;
    height: 72rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    flex-shrink: 0;
    
    &:active {
      transform: scale(0.9);
    }
    
    &.disabled {
      opacity: 0.5;
      background: #ddd;
    }
    
    .send-icon {
      font-size: 32rpx;
    }
  }
}

.bottom-spacer {
  height: 40rpx;
}
</style>

